import { Movie } from "../entities/Movie";
import { MovieSchema } from '../model';
import { IMovie } from "../public/interface";
import { Conditions } from "../entities/Condition";
import { ISearchResult } from "../public/interface";
import { plainToClass } from "class-transformer";

export default class MovieService {
  /**
  * @description: 新增电影
  * @author: jiangqi 2024-03-10 16:44:24
  * @param: movie
  */
  static async add(movie: object): Promise<IMovie | string[]> {
    // 1 转换为movie类
    const movieObj = Movie.plainToClass(Movie, movie)
    // 2 校验movie类
    const errMsgs = await movieObj.Validate()
    if (errMsgs.length > 0) {
      // 校验不通过
      return errMsgs
    } else {
      // 校验通过,
      const res = await MovieSchema.create(movieObj)
      return res
    }
  }

  /**
  * @description: 修改电影
  * @author: jiangqi 2024-03-10 16:46:58
  * @param: movie
  */
  static async update(movie: any): Promise<string[]> {
    // 1 转换为movie类
    const movieObj = Movie.plainToClass(Movie, movie)
    // 2 校验movie类
    const errMsgs = await movieObj.Validate(true)
    if (!movie.id) {
      return ['id不能为空']
    }
    if (errMsgs.length > 0) {
      // 校验不通过
      return errMsgs
    } else {
      // 校验通过,
      await MovieSchema.updateOne({ _id: movie.id }, movie)
      return errMsgs
    }
  }

  /**
  * @description: 删除电影
  * @author: jiangqi 2024-03-10 17:36:52
  * @param: id
  */
  static async delete(id: string): Promise<true> {
    const res = await MovieSchema.deleteOne({ _id: id })
    console.log('删除了', res)
    return true
  }

  /**
  * @description: 批量删除带指定字符的数据
  * @author: jiangqi 2024-03-17 22:10:38
  * @param: str
  */
  static async deleteMany(str: string): Promise<true> {
    await MovieSchema.deleteMany({ name: new RegExp(str) })
    return true
  }

  /**
  * @description: 查询电影
  * @author: jiangqi 2024-03-10 17:39:23
  * @param: id
  */
  static async findById(id: string): Promise<IMovie | null> {
    return await MovieSchema.findById(id)
  }

  /**
  * @description: 模糊查询
  * @author: jiangqi 2024-03-11 22:11:00
  * @param: conditions
  */
  static async find(conditions: object): Promise<ISearchResult<IMovie> | string[]> {
    // 转换
    const conditionObj = plainToClass(Conditions, conditions)
    // 校验
    const errMsgs = await conditionObj.Validate(true)
    if (errMsgs.length > 0) {
      return errMsgs
    }
    // 查询
    const movies = await MovieSchema.find({
      name: { $regex: new RegExp(conditionObj.keyWord) }
    }).skip((conditionObj.page - 1) * conditionObj.limit).limit(conditionObj.limit)

    const count = await MovieSchema.find({
      name: { $regex: new RegExp(conditionObj.keyWord) }
    }).countDocuments()

    return {
      data: movies,
      pages: conditionObj.limit,
      curPage: conditionObj.page,
      count
    }
  }
}
